package com.android.bonn.fast.drawable.tags;

import android.graphics.RectF;
import android.text.Layout;
import android.text.Selection;
import android.text.Spannable;
import android.text.method.BaseMovementMethod;
import android.view.MotionEvent;
import android.widget.TextView;

public class CustomClickMovementMethod extends BaseMovementMethod {


    public interface OnClickableSpan {
        boolean onClickableSpan(String text);
    }

    private OnClickableSpan onClickableSpan;

    public void setOnClickableSpan(OnClickableSpan onClickableSpan) {
        this.onClickableSpan = onClickableSpan;
    }

    private static CustomClickMovementMethod sInstance;

    public static CustomClickMovementMethod getInstance() {
        if (sInstance == null) {
            sInstance = new CustomClickMovementMethod();
        }
        return sInstance;
    }

    private final RectF touchedLineBounds = new RectF();

    @Override
    public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
        int action = event.getAction();
        if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) {
            int touchX = (int) event.getX();
            int touchY = (int) event.getY();
            touchX -= widget.getTotalPaddingLeft();
            touchY -= widget.getTotalPaddingTop();
            touchX += widget.getScrollX();
            touchY += widget.getScrollY();
            Layout layout = widget.getLayout();
            int line = layout.getLineForVertical(touchY);
            int off = layout.getOffsetForHorizontal(line, touchX);

            touchedLineBounds.left = layout.getLineLeft(line);
            touchedLineBounds.top = layout.getLineTop(line);
            touchedLineBounds.right = layout.getLineWidth(line) + touchedLineBounds.left;
            touchedLineBounds.bottom = layout.getLineBottom(line);

            RoundedTagSpan[] link = buffer.getSpans(off, off, RoundedTagSpan.class);
            if (link.length != 0 && touchedLineBounds.contains(touchX, touchY)) {
                if (action == MotionEvent.ACTION_UP) {
                    RoundedTagSpan selectSpan = link[0];
                    int csStart = buffer.getSpanStart(selectSpan);
                    int csEnd = buffer.getSpanEnd(selectSpan);
                    return onClickableSpan.onClickableSpan(buffer.subSequence(csStart, csEnd).toString());
                }
                return true;
            } else {
                Selection.removeSelection(buffer);
            }
        }
        return false;
    }

    @Override
    public void initialize(TextView widget, Spannable text) {
        Selection.removeSelection(text);
    }
}